import _Stores from "choerodon-ui/pro/lib/stores";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _DataSet from "choerodon-ui/pro/lib/data-set";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _Table from "choerodon-ui/pro/lib/table";
import _map from "lodash/map";
import React, { useContext, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import moment from 'moment';
import styles from "./style/index.less?modules";
import Store from "./stores";
import { getQueryFields } from "./utils";
var ToolBar = _Table.ToolBar,
    AdvancedQueryBar = _Table.AdvancedQueryBar;
var QueryBar = observer(function (_ref) {
  var searchId = _ref.searchId;

  var _useContext = useContext(Store),
      dataSet = _useContext.dataSet,
      listDataSet = _useContext.listDataSet,
      fields = _useContext.fields,
      _useContext$queryBar = _useContext.queryBar,
      queryBar = _useContext$queryBar === void 0 ? 'normal' : _useContext$queryBar,
      _useContext$queryFiel = _useContext.queryFieldsLimit,
      queryFieldsLimit = _useContext$queryFiel === void 0 ? 0 : _useContext$queryFiel;

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      props = _useState2[0],
      setProps = _useState2[1];

  var resetArr = [];
  var syncDataLength = listDataSet.filter(function (record) {
    return record.status === 'sync';
  }).length;

  function setQuery(name, value, comparator, type) {
    var vl = value;
    if (type === 'date') vl = moment(value).format('YYYY-MM-DD HH:mm:ss');
    dataSet.setQueryParameter("search.condition.".concat(name), "".concat(name.split('-')[0], ",").concat(comparator, ",").concat(vl));
    resetArr.push("search.condition.".concat(name));
  }

  function findLovParam(_x, _x2) {
    return _findLovParam.apply(this, arguments);
  }

  function _findLovParam() {
    _findLovParam = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(name, value) {
      var field, lovCode, valueField, config;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              field = dataSet.getField("".concat(name.split('-')[0]));

              if (!field) {
                _context2.next = 14;
                break;
              }

              lovCode = field.get('lovCode');
              valueField = field.get('valueField');

              if (!lovCode) {
                _context2.next = 13;
                break;
              }

              if (valueField) {
                _context2.next = 12;
                break;
              }

              _context2.next = 8;
              return _Stores.LovCodeStore.fetchConfig(lovCode);

            case 8:
              config = _context2.sent;
              return _context2.abrupt("return", {
                name: config.valueField,
                value: value[config.valueField]
              });

            case 12:
              return _context2.abrupt("return", {
                name: valueField,
                value: value[valueField]
              });

            case 13:
              return _context2.abrupt("return", {
                name: name,
                value: value
              });

            case 14:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));
    return _findLovParam.apply(this, arguments);
  }

  useEffect(function () {
    if (listDataSet.length) {
      var dsFields = fields || _map(Object.values(dataSet.fields.toJSON()), function (field) {
        return field.props;
      });

      var queryFields = listDataSet.find(function (record) {
        return record.get('searchId') === searchId;
      }).toData().queryList;
      var barFields = [];

      _map(queryFields, function (qField, index) {
        _map(dsFields, function (field) {
          if (qField.fieldName === field.name) {
            barFields.push(_objectSpread(_objectSpread({}, field), {}, {
              name: "".concat(field.name, "-").concat(index),
              type: field.type === 'intl' ? 'string' : field.type,
              defaultValue: qField.comparator
            }));
          }
        });
      });

      dataSet.props.queryFields = [];
      dataSet.props.queryDataSet = new _DataSet({
        fields: barFields,
        events: {
          update: function () {
            var _update = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) {
              var name, value, param, _barFields$filter$, defaultValue, type;

              return _regeneratorRuntime.wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      name = _ref2.name, value = _ref2.value;
                      _context.next = 3;
                      return findLovParam(name, value);

                    case 3:
                      param = _context.sent;

                      if (param.name.indexOf('search.condition') !== 0) {
                        _barFields$filter$ = barFields.filter(function (t) {
                          return t.name === name;
                        })[0], defaultValue = _barFields$filter$.defaultValue, type = _barFields$filter$.type;
                        setQuery(param.name, param.value, defaultValue, type);
                      }

                    case 5:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee);
            }));

            function update(_x3) {
              return _update.apply(this, arguments);
            }

            return update;
          }(),
          reset: function reset() {
            _map(resetArr, function (name) {
              dataSet.setQueryParameter(name, '');
            });
          }
        }
      });
      setProps({
        dataSet: dataSet,
        queryDataSet: dataSet.queryDataSet || dataSet.props.queryDataSet,
        buttons: [],
        queryFields: getQueryFields(dataSet),
        queryFieldsLimit: queryFieldsLimit
      });
    }
  }, [syncDataLength, searchId]);

  function renderBar() {
    if (typeof queryBar === 'function') {
      return queryBar(props);
    }

    switch (queryBar) {
      case 'normal':
        return /*#__PURE__*/React.createElement(ToolBar, Object.assign({
          key: "toolbar"
        }, props));

      case 'advancedBar':
        return /*#__PURE__*/React.createElement(AdvancedQueryBar, Object.assign({
          key: "advancedBar"
        }, props));

      default:
        return null;
    }
  }

  return /*#__PURE__*/React.createElement("div", {
    className: styles['sl-query']
  }, props && renderBar());
});
export default QueryBar;